package com.hanson.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.hanson.annotation.Log;
import com.hanson.common.api.CommonResult;
import com.hanson.mapper.UserMapper;
import com.hanson.mapper.UserRoleMapper;
import com.hanson.platform_api.properties.AliYunOSSProperties;
import com.hanson.pojo.vo.User;
import com.hanson.pojo.vo.UserRole;
import com.hanson.service.AliYunOSService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description: 阿里云oss对象存储服务接口
 * @classname: AliyunOOSController
 * @author: Hanson
 * @create: 2021/01/13
 **/
@Slf4j
@Api(tags = "阿里云oss对象存储服务接口")
@RestController
@Log
@RequestMapping("/dmall/aliyun/oss")
public class AliYunOOSController {

    @Autowired
    AliYunOSSProperties aliYunOSSProperties;
    @Autowired
    AliYunOSService aliYunOSService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    TencentCOSController tencentCOSController;

    //强制迁移oss至cos标志
    public final static int TRANSFER = 0;

    @ApiOperation("商品图片上传")
    @PostMapping("/goods/image/upload")
    @ResponseBody
    public CommonResult<Object> imageUpload(MultipartFile multipartFile){

        /*
        ----------身份验证,非管理员上传到temp临时文件夹-----------
         */
        String filePath = "temp";
        User principal = (User)(SecurityUtils.getSubject().getPrincipal());
        String userId = principal.getUserId();
        List<UserRole> userRoles = userRoleMapper.doGetUserRolesByUid(userId);
        //超级管理员角色
        Set<Integer> collect = userRoles.stream().map(UserRole::getRoleId).filter((d) -> d == 1).collect(Collectors.toSet());
        if (collect.size() == 1){
            filePath = "openfile";
        }
        /*
        ----------身份验证,非管理员上传到temp临时文件夹-----------
         */
        if (TRANSFER == 0){
            //迁移阿里云对象存储oss至腾讯云cos --2022
            return tencentCOSController.imageUpload(multipartFile);
        }


        String bucketName = aliYunOSSProperties.getBucketName();
        String fileHost = aliYunOSSProperties.getFileHost();
        OSSClient ossClient = null;
        try(InputStream fileInputStream = multipartFile.getInputStream()) {
            String fileName = multipartFile.getOriginalFilename();
            ossClient = getOSSClient(aliYunOSSProperties);
            String url = aliYunOSService.uploadMallImage(fileName, filePath, fileInputStream, ossClient, bucketName, fileHost, true);
            return new CommonResult<>(url);
        } catch (IOException e) {
            log.error("商城上传图片IO异常",e);
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }


    /**
    *
    * 获取阿里云Oss存储对象
    *
    * @params: [aliYunOSSProperties]
    * @param: aliYunOSSProperties
    * @return: {@link OSSClient}
    * @since: 2021/1/13
    **/
    private OSSClient getOSSClient(AliYunOSSProperties aliYunOSSProperties){
        String endpoint = aliYunOSSProperties.getEndpoint();
        String accesskeyId = aliYunOSSProperties.getAccesskeyId();
        String accesskeySecret = aliYunOSSProperties.getAccesskeySecret();
        return (OSSClient)new OSSClientBuilder().build(endpoint, accesskeyId, accesskeySecret);
    }
}
